package com.share.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.share.admin.mapper.RoleMapper;
import com.share.admin.model.db.Menu;
import com.share.admin.model.db.Role;
import com.share.admin.model.vo.RolePageReq;
import com.share.admin.service.IMenuService;
import com.share.admin.service.IRoleService;
import com.share.common.common.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色表  服务实现类
 * </p>
 *
 * @author author
 * @since 2022-09-22
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private IMenuService menuService;

    @Override
    public Set<Role> listByUserId(Long userId) {
        return roleMapper.selectRoleByUserId(userId);
    }

    @Override
    public Set<Role> listAll() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        return new HashSet<>(roleMapper.selectList(queryWrapper));
    }

    @Override
    public Page pageList(RolePageReq req) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(req.getName())) {
            queryWrapper.like(Role::getName, req.getName());
        }
        if (StringUtils.isNotBlank(req.getCode())) {
            queryWrapper.like(Role::getCode, req.getCode());
        }
        if (StringUtils.isNotBlank(req.getStatus())) {
            queryWrapper.like(Role::getStatus, req.getStatus());
        }

        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<Role> list = roleMapper.selectList(queryWrapper);
        Page<Role> page = new Page<>(list, new PageInfo<>(list).getTotal(), req);

        //查询角色关联的菜单
        for (Role role : list) {
            Long roleId = role.getId();
            Set<Menu> menus = menuService.listByRoleId(roleId);
            role.setMenus(menus);
        }
        return page;
    }

    @Override
    public Integer bindOrRemoveMenus(Boolean isBind, String roleId, List<String> menuIds) {
        if (isBind != null && isBind) {
            return roleMapper.bindMenus(roleId, menuIds);
        } else {
            return roleMapper.removeMenus(roleId, menuIds);
        }
    }
}
